package com.bw.session.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bw.common.constants.TokenConstants;
import com.bw.common.domain.User;
import com.bw.common.utils.JwtUtils;
import com.bw.session.domain.Scheduled;
import com.bw.session.domain.vo.SessionVO;
import com.bw.session.exception.BizException;
import com.bw.session.mapper.ScheduledMapper;
import com.bw.session.service.ScheduledService;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class ScheduledServiceImpl implements ScheduledService {

    @Autowired
    private ScheduledMapper scheduledMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public List<Scheduled> selectSession() {
        return scheduledMapper.selectScheduled();
    }

    @Override
    public void updateScheduled(Scheduled scheduled) {
        Scheduled scheduled1 = scheduledMapper.selectScheduledById(scheduled.getId());
        if (!getUserInfo().getId().equals(scheduled1.getUserId())){
            throw new BizException("你无法修改别人的记录");
        }
        scheduledMapper.updateScheduled(scheduled);
    }

    @Override
    public void deleteScheduled(Integer id) {
        Scheduled scheduled1 = scheduledMapper.selectScheduledById(id);
        if (!getUserInfo().getId().equals(scheduled1.getUserId())){
            throw new BizException("你无法删除别人的记录");
        }
        scheduledMapper.deleteScheduled(id);
    }

    @Override
    public void insertScheduled(Scheduled scheduled) {

        Date date = new Date();
        int hours = date.getHours();
        if (!((hours >= 8 && hours <= 12) || (hours >= 14 && hours <= 18))){
            throw new BizException("会议室预定时间为8.00-12.00 14.00-18.00 其余时间无法进行预约");
        }

        Scheduled scheduled1 = scheduledMapper.selectScheduledInfo(scheduled.getSessionId());
        if (scheduled1 != null){
            throw new BizException("该会议室已被预定,无法再次预约");
        }

        scheduledMapper.insertScheduled(scheduled);

    }


    public User getUserInfo(){
        String token = request.getHeader("token");
        String userKey = JwtUtils.getUserKey(token);
        String userInfo = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return JSONObject.parseObject(userInfo,User.class);
    }
}
